package services.helpers

import javax.inject.{Inject, Singleton}
import play.api.{Configuration, Logger}
import slick.codegen.SourceCodeGenerator

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class MySourceCodeGenerator @Inject()(private val conf: Configuration)(implicit ec: ExecutionContext) {

  private val profile = conf.getOptional[String]("slick.dbs.default.profile").getOrElse("")
  private val jdbcDriver = conf.getOptional[String]("slick.dbs.default.db.driver").getOrElse("")
  private val url = conf.getOptional[String]("slick.dbs.default.db.url").getOrElse("")
  private val outputFolder = conf.getOptional[String]("app.default.dao.output.path").getOrElse("")
  private val pkg = conf.getOptional[String]("app.default.dao.output.pkg").getOrElse("")
  private val user = conf.getOptional[String]("slick.dbs.default.db.username").getOrElse("")
  private val password = conf.getOptional[String]("slick.dbs.default.db.password").getOrElse("")

  private val logger = Logger.apply(this.getClass.getSimpleName).logger

  private def getStandardProfile(profile: String) = profile.replace("$", "")

  def initializeTables(): Future[Boolean] = Future {
    val properties = Array[String](
      getStandardProfile(profile),
      jdbcDriver,
      url,
      outputFolder,
      pkg,
      user,
      password
    )

    try {
      SourceCodeGenerator.main(properties)
      true
    } catch {
      case e: Exception =>
        logger.info(e.getMessage)
        false
    }
  }
}
